<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '基金详情',
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <PageLayout :navbarShow="false">
    <!--刘海处理-->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    <scroll-view :scroll-y="true" class="content" :show-scrollbar="false">
      <view style="padding-top: 10px">
        <wd-row>
          <wd-col :span="16">
            <view style="padding-top: 20rpx; padding-left: 22px">
              <view style="font-size: 36rpx; font-weight: 600">基金详情</view>
              <view style="display: flex; flex-wrap: wrap">
                <view style="margin-right: 4px">
                  <wd-tag color="#0083ff" bg-color="#d0e8ff">
                    {{ detailModel.managerCompany }}
                  </wd-tag>
                </view>
                <view style="margin-right: 4px">
                  <wd-tag color="#0083ff" bg-color="#d0e8ff">
                    {{ detailModel.manager }}
                  </wd-tag>
                </view>
                <view style="margin-right: 4px">
                  <wd-tag color="#0083ff" bg-color="#d0e8ff">
                    {{ detailModel.type }}
                  </wd-tag>
                </view>
                <view style="margin-right: 4px">
                  <wd-tag color="#0083ff" bg-color="#d0e8ff">
                    {{ detailModel.subType }}
                  </wd-tag>
                </view>
                <view style="margin-right: 4px">
                  <wd-tag color="#0083ff" bg-color="#d0e8ff">
                    {{ detailModel.risk }}
                  </wd-tag>
                </view>
                <view style="margin-right: 4px">
                  <wd-tag color="#0083ff" bg-color="#d0e8ff">
                    {{ detailModel.code }}
                  </wd-tag>
                </view>
                <view style="margin-right: 4px">
                  <wd-tag color="#0083ff" bg-color="#d0e8ff">
                    成立：{{ detailModel.buildDate }}
                  </wd-tag>
                </view>
              </view>
            </view>
          </wd-col>
          <wd-col :span="8">
            <image src="../../static/detail-bg.png" style="height: 80px; width: 100px"></image>
          </wd-col>
          <wd-col :span="24">
            <view class="box" style="margin-top: 5px">
              <view style="font-weight: 600; margin-bottom: 10rpx; font-size: 30rpx">
                {{ detailModel.name }}
              </view>
              <wd-row>
                <wd-col :span="12">
                  <view
                    style="height: 50rpx; font-size: 36rpx; line-height: 50rpx; font-weight: 600"
                    :style="{ color: detailModel.syl1n >= 0 ? 'red' : 'green' }"
                  >
                    {{ detailModel.syl1n ? detailModel.syl1n.toFixed(2) : '--' }}%
                  </view>
                  <view style="font-size: 26rpx">近1年涨幅</view>
                </wd-col>
                <wd-col :span="6">
                  <view
                    style="height: 50rpx; line-height: 50rpx; text-align: center; font-weight: 600"
                    :style="{
                      color:
                        (detailModel.estimateRate == null
                          ? detailModel.nowRate
                          : detailModel.estimateValDate == detailModel.valDate
                            ? detailModel.nowRate
                            : detailModel.estimateRate) > 0
                          ? 'red'
                          : 'green',
                    }"
                  >
                    {{
                      (detailModel.estimateRate == null
                        ? detailModel.nowRate
                        : detailModel.estimateValDate == detailModel.valDate
                          ? detailModel.nowRate
                          : detailModel.estimateRate
                      ).toFixed(2)
                    }}%
                  </view>
                  <view style="font-size: 26rpx; text-align: center">日涨幅</view>
                </wd-col>
                <wd-col :span="6">
                  <view
                    style="height: 50rpx; line-height: 50rpx; text-align: center; font-weight: 600"
                  >
                    {{ detailModel.nowVal }}
                  </view>
                  <view style="font-size: 26rpx; text-align: center">单位净值</view>
                </wd-col>
              </wd-row>
            </view>
          </wd-col>
        </wd-row>
      </view>
      <!--分隔线-->
      <wd-gap></wd-gap>

      <view class="tab-box">
        <view
          v-for="(item, index) in tabList"
          :key="index"
          class="tab-box-item"
          :style="{
            backgroundColor: tabKey == item.key ? '#fff' : '',
            color: tabKey == item.key ? '#0083ff' : '',
          }"
          @click="tabKey = item.key"
        >
          <view v-if="lineType == 'hold'" style="margin-bottom: 10rpx">
            {{ item.name }}
          </view>
          <view
            v-if="tabKey == item.key && lineType == 'hold'"
            style="
              width: 30rpx;
              height: 2px;
              background-color: #0083ff;
              margin: 0 auto;
              border-radius: 1rpx;
            "
          ></view>
        </view>
      </view>
      <view class="box" style="border-radius: 0rpx 0rpx 10rpx 10rpx">
        <!--净值趋势-->
        <fund-val-chart
          :lineType="lineType"
          :id="fundId"
          :key="chartKey"
          v-if="tabKey === 1"
        ></fund-val-chart>
        <!--买卖点-->
        <fund-buy-chart
          :lineType="lineType"
          :optId="optId"
          v-else-if="tabKey === 2"
        ></fund-buy-chart>
      </view>

      <!--数据分析-->
      <view v-if="lineType == 'hold'">
        <!--分隔线-->
        <wd-gap></wd-gap>

        <view class="box">
          <!--标题组件-->
          <FundTitle title="数据分析" />
          <!--数据分析-->
          <FundAccountAnalyse />
        </view>
      </view>

      <!--分隔线-->
      <wd-gap></wd-gap>

      <view class="box">
        <!--标题组件-->
        <FundTitle title="外部基金" desc="跳转至天天基金" />

        <view
          style="border: 1px solid #f2f2f2; padding: 10rpx 20rpx; border-radius: 4rpx"
          @click="onClickLink('xqjj')"
        >
          雪球基金
        </view>

        <view
          style="
            border: 1px solid #f2f2f2;
            padding: 10rpx 20rpx;
            border-radius: 4rpx;
            margin-top: 20rpx;
          "
          @click="onClickLink('ths')"
        >
          同花顺爱基金
        </view>

        <view
          style="
            border: 1px solid #f2f2f2;
            padding: 10rpx 20rpx;
            border-radius: 4rpx;
            margin-top: 20rpx;
          "
          @click="onClickLink('ttjj')"
        >
          天天基金
        </view>
      </view>

      <!--分隔线-->
      <wd-gap></wd-gap>

      <view class="box">
        <!--标题组件-->
        <FundTitle title="波段定投收益" desc="依据减仓线动态调整波段收益！" />
        <!--空数据提示-->
        <wd-status-tip
          image="../../static/content.png"
          tip="暂无波段数据"
          v-if="waveList.length == 0"
        />
        <!--波段-->
        <view class="wave" v-else>
          <!--表头-->
          <view
            style="
              border-bottom: 1px solid #f2f2f2;
              padding-bottom: 10rpx;
              color: #8a8a8a;
              font-size: 22rpx;
            "
          >
            <wd-row>
              <wd-col :span="10">
                <view style="text-align: left">时间</view>
              </wd-col>
              <wd-col :span="4">定投次数</wd-col>
              <wd-col :span="5">定投收益率</wd-col>
              <wd-col :span="5">常规收益率</wd-col>
            </wd-row>
          </view>
          <!--数据列表-->
          <view
            style="border-bottom: 1px solid #f2f2f2; padding-bottom: 20rpx; padding-top: 20rpx"
            v-for="data in waveList"
            :key="data"
          >
            <wd-row>
              <wd-col :span="10">
                <view style="color: #454545; font-size: 24rpx; text-align: left">
                  {{ moment(data.addStartTime).format('YY/MM/DD') }}
                  ~
                  {{ moment(data.addEndTime).format('YY/MM/DD') }}
                </view>
              </wd-col>
              <wd-col :span="4">
                <view>
                  {{ data.addList.length }}
                </view>
              </wd-col>
              <wd-col :span="5">
                <view :style="{ color: parseFloat(data.syl) >= 0 ? 'red' : 'green' }">
                  {{ parseFloat(data.syl) >= 0 ? '+' + data.syl : data.syl }}
                </view>
              </wd-col>
              <wd-col :span="5">
                <view :style="{ color: parseFloat(data.currentRate) >= 0 ? 'red' : 'green' }">
                  {{
                    parseFloat(data.currentRate) >= 0 ? '+' + data.currentRate : data.currentRate
                  }}
                </view>
              </wd-col>
            </wd-row>
          </view>
        </view>
        <view
          style="padding: 0rpx 0px; text-align: center; color: gray; font-size: 24rpx"
          v-if="waveList.length > 0"
          @click="onClickMoreWave"
        >
          查看更多
        </view>
      </view>
      <!--分隔线-->
      <wd-gap></wd-gap>

      <view class="box">
        <FundStageSy :id="fundId" />
      </view>
      <!--分隔线-->
      <wd-gap></wd-gap>
    </scroll-view>

    <!--工具栏-->
    <view class="tool">
      <!--自定义配置-->
      <view class="random-box">
        <view class="btn" @click="onClickSettings">
          <wd-icon name="setting" />
          <view>更多</view>
        </view>
        <view class="btn" @click="onClickNote">
          <wd-icon name="clock" />
          <view>提醒</view>
        </view>

        <view class="btn" v-if="lineType == 'optional'" @click="onClickHold">
          <wd-icon name="fork" />
          <view>持有</view>
        </view>

        <view class="btn" v-else @click="onClickTradeRecord">
          <wd-icon name="view-list" />
          <view>交易明细</view>
        </view>
      </view>

      <!--自选工具栏-->
      <view v-if="lineType === 'optional'" class="choose-box">
        <view class="choose-btn" v-if="showSelected" @click="onClickSelect">加入自选</view>
        <view
          class="choose-btn"
          v-else
          style="background-color: #63b8ff"
          @click="onClickCancelSelect"
        >
          取消自选
        </view>
      </view>

      <!--持有工具栏-->
      <view v-else class="hold-box">
        <view
          class="btn"
          style="background: linear-gradient(to right, #ff8272, #ff5843)"
          @click="onClickAddReduce(1)"
        >
          减仓
        </view>
        <view
          class="btn"
          style="background: linear-gradient(to right, #63b8ff, #0083ff)"
          @click="onClickAddReduce(0)"
        >
          加仓
        </view>
      </view>
    </view>

    <!--自定义配置-->
    <wd-popup
      v-model="showZdySettings"
      position="bottom"
      custom-style="border-radius: 20rpx 20rpx 0px 0px"
    >
      <!--弹窗内容-->
      <FundSettingsPop
        :lineType="lineType"
        :id="fundId"
        :optId="optId"
        :key="chartKey"
        @change="onPopChange"
      ></FundSettingsPop>
    </wd-popup>
  </PageLayout>
</template>

<script lang="ts" setup>
import { http } from '@/utils/http'
import moment from 'moment'
import FundValChart from './component/fund-val-chart.vue'
import FundSettingsPop from './component/fund-settings-pop.vue'
import FundBuyChart from './component/fund-buy-chart.vue'
import FundTitle from './component/fund-title.vue'
import FundAccountAnalyse from './component/fund-account-analyse.vue'
import FundStageSy from './component/fund-stage-sy.vue'
import { useToast } from 'wot-design-uni'

// 用于刷新子组件
const chartKey = ref(0)
// 详情
const detailModel = ref({
  syl1n: 0,
  nowVal: 0,
  estimateRate: 0,
  nowRate: 0,
  name: '',
  code: '',
  estimateValDate: '',
  valDate: '',
  managerCompany: '',
  risk: '',
  type: '',
  manager: '',
  subType: '',
  buildDate: '',
})
// 消息提示
const toast = useToast()
// tabKey
const tabKey = ref(1)
// 基金趋势数组
const tabList = ref([
  { key: 1, name: '单位净值' },
  { key: 2, name: '加减仓点' },
  { key: 3, name: '收益趋势' },
])
// 是否显示自定义配置
const showZdySettings = ref(false)
// 高度
const statusBarHeight = ref(15)
// 基金自选ID
const optId = ref()
// 基金ID
const fundId = ref()
// 是否显示自选按钮
const showSelected = ref(false)
// 线类型
const lineType = ref('')
// 波段数据
const waveList = ref([])
// 点击加减仓
const onClickAddReduce = (type) => {
  uni.navigateTo({
    url: '/pages/hold/buy?holdId=' + optId.value + '&type=' + type,
  })
}

// 交易记录
const onClickTradeRecord = () => {
  uni.navigateTo({
    url: '/pages/detail/trade-record?holdId=' + optId.value,
  })
}

// 计算百分数
const converToPercent = (data: number, fixeds: number) => {
  const percents = (data * 100).toFixed(fixeds)
  return `${percents}%`
}

const onClickLink = (type) => {
  // 跳转地址
  let url = ''
  // 代码
  const code = detailModel.value.code
  if (type === 'ttjj') {
    url = 'https://h5.1234567.com.cn/app/fund-details/?fCode=' + code
  } else if (type === 'ths') {
    url = 'https://trade.5ifund.com/app/wechat/dist/detail.html?operator=915#/' + code
  } else if (type === 'xqjj') {
    url = 'https://danjuanfunds.com/funding/' + code
  }
  // 发起跳转
  window.open(url, '_self')
}

// 加载波段数据
const loadWaveData = () => {
  const params = { fundId: fundId.value }
  http.get('/sys/fund/optional/queryWave', params).then((res: any) => {
    if (res.success) {
      // 倒序
      const result = res.result.reverse()
      // 取数
      const end = result.length > 6 ? 6 : result.length > 0 ? result.length - 1 : 0
      // 赋值
      waveList.value = result.splice(0, end)
      // 遍历波段
      for (let i = 0; i < waveList.value.length; i++) {
        // 读取波段数据
        const item = waveList.value[i]
        // 常规涨幅:定投的最后一天与定投的第一天的收益率差额
        const currentRate = converToPercent(
          (item.addList[item.addList.length - 1] - item.addList[0]) / item.addList[0],
          2,
        )
        // 计算总份额
        let totalCount = 0
        // 循环遍历定投份额
        item.addList.forEach((ad) => {
          totalCount += 1000 / ad
        })
        // 计算总定投额：默认每次定投额为1000元
        const totalMoney = item.addList.length * 1000
        // 计算定投收益
        item.buyRate = converToPercent(
          (totalCount * item.addList[item.addList.length - 1] - totalMoney) / totalMoney,
          2,
        )
        // 设置常规涨幅
        item.currentRate = currentRate
        // 差额涨幅
        item.rate = (parseFloat(item.buyRate) - parseFloat(item.currentRate)).toFixed(2) + '%'
        // 日期差额
        item.dateDiff = moment(item.addEndTime).diff(moment(item.addStartTime), 'days') + 1
        // 卖出总额
        let mcMoney = 0
        let mcRate = 0
        // 5次平均法
        for (let t = 0; t < item.jcList.length && t < 5; t++) {
          mcMoney += totalCount * 0.2 * item.jcList[t]
          mcRate += 0.2
        }
        // 收益金额
        item.syMoney = (mcMoney - totalMoney * mcRate).toFixed(2)
        // 收益率
        item.syl = converToPercent(item.syMoney / (totalMoney * mcRate), 2)
      }
    }
  })
}

// 点击 自定义配置
const onClickSettings = () => {
  if (lineType.value === 'optional') {
    if (showSelected.value !== true) {
      showZdySettings.value = true
    } else {
      toast.warning('请先添加自选')
    }
  }
}

// 点击取消自选
const onClickCancelSelect = () => {
  http.get('/sys/fund/optional/delete', { id: optId.value }).then((res: any) => {
    if (res.success) {
      showSelected.value = true
      toast.success('取消成功')
    }
  })
}
// 添加自选
const onClickSelect = () => {
  http.post('/sys/fund/optional/add', { fundId: fundId.value }).then((res: any) => {
    if (res.success) {
      showSelected.value = false
      optId.value = res.result.id
      toast.success('添加成功')
    } else {
      toast.error(res.message)
    }
  })
}

// 加载详情
const loadDetail = () => {
  http.get('/sys/fund/library/detail', { id: fundId.value }).then((res: any) => {
    if (res.success) {
      // 日期格式化处理
      res.result.buildDate = moment(res.result.buildDate).format('YYYY-MM-DD')
      detailModel.value = res.result
    }
  })
}

// 弹窗内容更新成功
const onPopChange = () => {
  // 关闭弹窗
  showZdySettings.value = false
  // 刷新图表
  chartKey.value += 1
}

// 点击更多波段数据
const onClickMoreWave = () => {
  uni.navigateTo({
    url: '/pages/detail/component/fund-wave-list',
  })
}

// 点击提醒
const onClickNote = () => {
  toast.info('功能开发中~')
}

// 点击持有
const onClickHold = () => {
  toast.info('功能开发中~')
}

onLoad((option) => {
  const SYSTEM_INFO = uni.getSystemInfoSync()
  statusBarHeight.value = SYSTEM_INFO.statusBarHeight
  fundId.value = option.fundId
  optId.value = option.optId
  lineType.value = option.lineType

  // 加载波段数据
  loadWaveData()
  // 加载详情
  loadDetail()
})
</script>

<style lang="scss" scoped>
.content {
  background: linear-gradient(to bottom, #daf0fe, #f9fbfb);
  .tab-box {
    display: flex;
    width: 95%;
    margin: 0 auto;
    text-align: center;
    background-color: #fff;
    font-size: 25rpx;
    border-radius: 12rpx 12rpx 0rpx 0rpx;
    color: #454545;
    .tab-box-item {
      flex: 1;
      padding-top: 28rpx;
      border-radius: 12rpx 12rpx 0rpx 0rpx;
    }
  }
  .box {
    width: 95%;
    margin: 0 auto;
    border-radius: 16rpx;
    background-color: #fff;
    padding: 20rpx 15rpx;

    .fu-date {
      width: 90%;
      margin: 2px auto;
      text-align: center;
      border: 1px solid #f4f5f7;
      padding: 14rpx 0px;
      border-radius: 15px;
      font-size: 24rpx;
    }
    .fu-date-active {
      background-color: #e9f0ff;
      color: #0083ff;
    }
    .fu-title-box {
      display: flex;
      margin-bottom: 10px;
      align-items: center;
      .fu-title-x {
        width: 12rpx;
        height: 30rpx;
        border-radius: 5px;
        background-color: #0083ff;
        margin-right: 4px;
      }
      .fu-title-name {
        font-weight: 700;
        font-size: 26rpx;
      }
    }
    .wave {
      border-radius: 10rpx;
      padding: 14rpx;
      margin: 10rpx 0rpx;
      font-size: 26rpx;
      text-align: center;
    }
  }
}
.tool {
  display: flex;
  padding: 20rpx 10px;
  background-color: #fff;
  justify-content: space-between;
  font-size: 24rpx;
  // border-radius: 40rpx 40rpx 0px 0px;
  .random-box {
    flex: 2;
    display: flex;
    padding: 0px 30rpx;
    .btn {
      flex: 1;
      text-align: center;
    }
  }
  .choose-box {
    flex: 2;
    .choose-btn {
      color: #fff;
      background-color: #207bf1;
      text-align: center;
      border-radius: 30rpx;
      padding: 16rpx 0rpx;
    }
  }
  .hold-box {
    flex: 2;
    display: flex;
    .btn {
      flex: 1;
      color: #fff;
      background-color: #207bf1;
      text-align: center;
      border-radius: 30rpx;
      padding: 16rpx 0rpx;
      margin: 0px 16rpx;
    }
  }
}
</style>
